<?php
/**
 * 数据库连接适配器
 *
 * @author Mo yi <root@imoi.cn>
 * @link   http://www.imoi.cn
 * @copyright Copyright &copy; 2010-2012 DuoLam Software LLC
 * @license http://www.imoi.cn/license/
 * @version $Id: dpDbConnect.php 2799 2012-04-10 14:41:54Z Mo.yi $
 * @package db
 * @since 1.0
 */

class dpDbConnect extends dpComponent
{

	/**
	 * 数据库连接器
	 */
	public    $connect = array();

	/**
	 * 配置信息
	 */
	protected $config  = array(); 

	/**
	 * 构造函数
	 */
	public function __construct()
	{
		$this->config = $this->setConfig('component','db');

		if (empty($this->config)) dpException::error('数据库配置信息不完善，无法启动，dpDbConnect');
	}

	/**
	 * 数据库连接器
	 * @param string $name   连接名
	 * @param array  $config 配置信息
	 * @return object 数据对象
	 */
	public function dbConnect($name,$config)
	{
		$driver = $config['driver'];
		$type   = null;

		if (stripos($driver,'pdo') !== false) {
			$param  = explode(':',$driver);
			$driver = $param[0];
			$config['type'] = $param[1];
			unset($param);
		}

		$class  = 'dp' . ucfirst($driver).'Driver';

		if (!isset($this->connect[$name]) or !is_object($this->connect[$name]))
			$this->connect[$name] = new $class($name,$config);

		return $this->connect[$name];
	}

	/**
	 * 魔术方法，用于连接直接连接主从库
	 */
	public function __get($name)
	{
		if ($name == 'master' or empty($name)) {
			return $this->dbConnect('master',$this->config['master']);
		} else if (isset($this->config['slave'][$name])) {
			return $this->dbConnect($name,$this->config['slave'][$name]);
		} else
			dpException::error('调用了不存在的从库数据连接适配器，'.$name.'，dpDbConnect');
	}

	public function __set($name,$value)
	{
		$this->$name = $value;
	}
}

?>